import React, { Component } from 'react';
import { Switch, InputNumber, Modal, Form, Space, Button, Input, Select, message } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheSwitch from "@/components/TheSwitch";
import TheTableExtend from "@/components/TheTableExtend";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '../../../components/TheQueryForm';
import { pageTabCategory, tabUpdateStatus, tabUpdateSort, viewTabCategory, addTabCategory, editTabCategory, dynamicLabelList } from '@/request/petCircleUtil/tab'
import store from "@/store/store"
import _ from 'lodash';

const { Option } = Select
export default class Tab extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef()
    this.state = {
      dataSource: [], //表格数据 
      columns: [
        {
          title: "tab名称",
          dataIndex: "categoryName",
          key: "categoryName",
        },
        {
          title: "排序",
          dataIndex: "sort",
          key: "sort",
          sorter: true,
          render: (text, record) => {
            return <InputNumber value={record.sort} onChange={this.valueInput} onBlur={() => this.onBlur(record.categoryId)} />
          }
        },
        {
          title: "标签",
          dataIndex: "labelNames",
          key: "labelNames",
        },
        {
          title: "备注",
          dataIndex: "remark",
          key: "remark",
        },
        {
          title: "修改时间",
          dataIndex: "updateTime",
          key: "updateTime",
          sorter: true,
          render: (text, record) => { return text }
        },
        {
          title: "修改人",
          dataIndex: "updateUserName",
          key: "updateUserName",
        },
        {
          title: "操作",
          dataIndex: "goodsName",
          key: "goodsName",
          fixed: 'right',
          render: (text, record) => {
            return record.categoryName === '推荐' || record.categoryName === '汪汪社' || record.categoryName === '喵喵社' || record.categoryName === '关注' ? '' : <TheButton  haspermi={['petCircleUtil:tab:edit']} onClick={() => this.edit(record.categoryId)}>编辑</TheButton>
          }
        },
        {
          title: "是否启用",
          dataIndex: "status",
          key: "status",
          fixed: 'right',
          render: (text, record) => {
            return <TheSwitch haspermi={['petCircleUtil:tab:switch']} checked={record.status} disabled={record.categoryName === '推荐' || record.categoryName === '汪汪社' || record.categoryName === '喵喵社' || record.categoryName === '关注' ? true : false} onChange={(v) => this.onStatusChange(v, record.sort, record.categoryId)} />
          }
        },
      ],
      newColumns: [], //重新配置表头
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 1,
      form_show: true, // 是否显示搜索
      searchOption: [
        { field: 'categoryName', label: 'tab名称', placeholder: '请输入tab名称', required: false, rules: [], type: 'Input' },
        {
          field: 'status', label: '启用状态', placeholder: '全部', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '-1' }, { label: '启用', value: '1' }, { label: '关闭', value: '0' },]
        },

      ],
      queryForm: {},
      title: '', //弹框标题
      isModalVisible: false, // 弹框是否显示
      categoryId: '', //编辑id
      tagsList: [], // 标签列表
      changeFlag: false, // 排序修改状态
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'tab') {
      this.setState({
        queryForm,
        pageData: {
          current: pageNo, size: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      this.getData()
    }
  }
  // table列表
  getData = async (values) => {
    if (values && 'status' in values) {
      if (values.status === '-1') { delete values.status }
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = { ...this.state.queryForm, ...this.state.pageData, }
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'tab', ...params }
      })
      console.log(params);
      let res = await pageTabCategory({ ...params })
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  // 搜索
  onFormSearch(values) {
    this.setState({ pageData: { pageNo: 1, pageSize: 10 } }, () => { this.getData(values) })
  }
  // 重置搜索
  onReset() {
    this.setState({ queryForm: {}, }, () => { this.pageChange(1, 10) })
  }
  // 标签列表
  async getDynamicLabelList() {
    let res = await dynamicLabelList()
    if (res.code === 0) {
      this.setState({ tagsList: res.data })
    }
  }
  // 排序输入框
  valueInput = (e) => {
    this.setState({ sort: e, changeFlag: true })
  }
  // 输入框失去焦点
  onBlur = async (categoryId) => {
    //如果没有修改 就不调用
    if (!this.state.changeFlag) return
    this.setState({ changeFlag: false })
    let { sort } = this.state
    // 排序数据修改
    const res = await tabUpdateSort({ categoryId, sort })
    if (res.code === 0) {
      message.success("排序修改成功")
      this.getData()
    }
  }
  //启用/停用
  onStatusChange = async (flag, sort, categoryId) => {
    console.log(flag, sort, categoryId);
    if (sort <= 0 || !sort) {
      return message.error('请配置排序规则')
    } else {
      const status = flag ? 1 : 0
      const res = await tabUpdateStatus({ categoryId: categoryId, status })
      if (res.code === 0) {
        this.getData()
      }
    }
  }
  // 新建
  add() {
    this.setState({
      isModalVisible: true,
      title: '新建tab分类'
    }, () => {
      this.getDynamicLabelList()
    })
  }
  // 编辑
  edit(categoryId) {
    this.setState({
      isModalVisible: true,
      title: '编辑tab分类',
      categoryId: categoryId,
    }, () => {
      this.tabView(categoryId)
      this.getDynamicLabelList()
    })
  }
  // tab分类详情
  tabView = async (values) => {
    let res = await viewTabCategory({ categoryId: values })
    if (res.code === 0) {
      this.FormRef.current.setFieldsValue({
        categoryName: res.data.categoryName,
        labelIdList: res.data.relationLabelIdList,
        remark: res.data.remark
      })
    }
  }
  // 取消
  handleCancel = () => {
    this.FormRef.current.resetFields()
    this.setState({
      isModalVisible: false,
    })
  };
  // 确定新增/修改
  handleFinish = async () => {
    const values = this.FormRef.current.getFieldsValue()
    if (this.state.categoryId) {
      let res = await editTabCategory({ ...values, categoryId: this.state.categoryId })
      if (res.code === 0) {
        React.$message({
          type: 'success',
          content: '修改成功'
        })
        this.handleCancel()
        this.getData()
      }

    } else {
      let res = await addTabCategory({ ...values })
      if (res.code === 0) {
        React.$message({
          type: 'success',
          content: '新建成功'
        })
        this.handleCancel()
        this.getData()
      }
    }

  };
  // 分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize,
      },
    }, () => {
      this.getData()
    })
  };
  // 表头显示内容
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  // 表格升序降序
  handleTableChange = (pagination, filters, sorter) => {
    let { queryForm } = this.state
    queryForm.orderByAsc = sorter.order === 'ascend' ? sorter.field !== 'updateTime' ? sorter.field : 'update_time' : null
    queryForm.orderByDesc = sorter.order === 'descend' ? sorter.field !== 'updateTime' ? sorter.field : 'update_time' : null
    this.setState({ queryForm }, () => { this.getData() })
  }
  render() {
    const { dataSource, columns, newColumns, total, pageData, form_show, searchOption, isModalVisible, title, tagsList } = this.state
    return (
      <div className="p-layout-box commodity-content">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton haspermi={['petCircleUtil:tab:add']} type={'primary'} size={'middle'} onClick={() => { this.add() }}>新建</TheButton>
        </TheTableExtend>
        <TheTable
          scroll={{ x: "max-content", y: "63vh" }}
          columns={newColumns}
          dataSource={dataSource}
          onChange={this.handleTableChange}
        />
        <ThePagination
          pageNo={pageData.pageNo}
          pageSize={pageData.pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        <Modal title={title} visible={isModalVisible} width="30%"
          onCancel={() => this.handleCancel()}
          footer={null}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.handleFinish(values)}
          >
            <Form.Item
              label="tab名称"
              name="categoryName"
              rules={[
                {
                  required: true,
                  message: '请输入tab名称!',
                },
              ]}
              tooltip="会展示到宠圈前台页面:非固定tab需要人工配置动态关联tab分类,才会在该tab下展示内容"
            >
              <Input placeholder='请输入tab名称' />
            </Form.Item>
            <Form.Item
              label="标签"
              name="labelIdList"
            >
              <Select
                placeholder="请选择标签"
                mode="multiple"
                optionFilterProp="children"
                filterOption={(input, option) => this.selectFilter(input, option)}
              >
                {
                  tagsList.map(item => <Option value={item.labelId}>{item.labelName}</Option>)
                }
              </Select>

            </Form.Item>
            <Form.Item
              label="备注"
              name="remark"
            >
              <Input placeholder='请输入备注' />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>

                <Button type="default" onClick={() => this.handleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
